package com.lsk.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;


import com.lsk.util.*;


/**
 * 移动端授权拦截器
 * Created by Administrator on 2018/9/14 0014.
 */

public class MobileAuthorizationInterceptor implements Interceptor {

    Cache cache= Redis.use();

    @Override
    public void intercept(Invocation ivo) {

        Controller controller=ivo.getController();

        String heardToken=controller.getHeader("token");

        String cookieToken=controller.getCookie("token");

        if (heardToken  ==null && cookieToken!=null){//网页模式

            Object o=cache.get(cookieToken);

            if (o==null){


                controller.redirect("/mobile/toRegisterPage");

            }else {

                cache.setex(cookieToken,60*30,o);

                String type=controller.getCookie("type");

                controller.setCookie("type",type,60*60*24);

                controller.setCookie("token",cookieToken,60*60*24);

                ivo.invoke();
            }


        }else if (cookieToken==null && heardToken==null){
            controller.redirect("/mobile/toRegisterPage");

        }else {//请求头模式

            if (heardToken==null){

                ReturnData returnData=new ReturnData(false);

                returnData.setMsg("没有token值，拒绝服务");

                returnData.setCode("-1");

                controller.renderJson(returnData);

            }else {
                Object o=cache.get(heardToken);

                if (o==null){

                    ReturnData returnData=new ReturnData(false);

                    returnData.setMsg("token过期，请重新登录");

                    controller.renderJson(returnData);

                }else {
                    ivo.invoke();
                }
            }


        }




    }



}
